package com.scse.bms.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.scse.bms.domain.UserHeadImgVO;
import com.scse.bms.entity.HeadImgDO;
import com.scse.bms.entity.UserHeadImgDO;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @Title: HeadImgMapper
 * @Author: 吴赠禹
 * @Date: 2021/2/27 21:08
 * @Version: 1.0
 * @Description: 操作头像
 */

@Mapper
@Repository
public interface HeadImgMapper extends BaseMapper<UserHeadImgVO> {


    /**
     * 根据用户ID获取头像
     *
     * @param userId
     * @return
     */
    @Select("select src FROM " +
            "t_user u LEFT JOIN t_user_head_img uh on u.id = uh.user_id " +
            "LEFT JOIN t_head_img h on uh.head_img_id = h.id  " +
            "where u.id = #{userId}")
    UserHeadImgVO getHeadImgVOByUserId(Integer userId);


    /**
     * 获取头像列表（分页）
     *
     * @return
     */
    @Select("select id,src, ifnull(userNum, 0) as userNum,upload_time FROM " +
            "(select head_img_id,count(head_img_id) as userNum  " +
            "from t_user_head_img group by head_img_id) a " +
            "right join t_head_img b on a.head_img_id = b.id")
    IPage<UserHeadImgVO> getHeadImgVOList(Page<?> page);


    /**
     * 插入头像记录（头像表，只保存头像）
     *
     * @param headImg
     * @return
     */
    @Insert("insert into t_head_img(src, upload_time) values(#{src}, #{uploadTime})")
    int insertHeadImg(HeadImgDO headImg);


    /**
     * 从数据库中随机选择10个头像供用户选择
     *
     * @return
     */
    @Select("select id, src from t_head_img where src != #{src} order by rand() limit 10")
    List<HeadImgDO> selectHeadImgRandomLimit10(@Param("src") String src);


    /**
     * 查询用户是否有头像（若有，则返回用户-头像ID，无则返回null）
     * @param userId
     * @return
     */
    @Select("select id from t_user_head_img where user_id = #{userId}")
    Integer selectUserIfExistProfile(@Param("userId") Integer userId);


    /**
     * 用户添加头像
     * @param userHeadImgDO
     * @return
     */
    @Insert("insert into t_user_head_img(user_id, head_img_id) values(#{userId}, #{headImgId})")
    int addUserProfile(UserHeadImgDO userHeadImgDO);


    /**
     * 用户修改头像
     * @param userHeadImgDO
     * @return
     */
    @Update("update t_user_head_img set head_img_id = #{headImgId} where user_id = #{userId}")
    int updateUserProfile(UserHeadImgDO userHeadImgDO);

}
